#include "tageditor.h"

TagEditor::TagEditor(QWidget *parent)
    : QDialog(parent)
{
    ui.setupUi(this);
    fileslst=NULL;
    tagslst=NULL;
}

TagEditor::~TagEditor()
{
    if (fileslst!=NULL) {
        fileslst->removeAll();
        delete fileslst;
    }
    if (tagslst!=NULL) {
        tagslst->removeAll();
        delete tagslst;
    }
}

void TagEditor::on_userOption_accepted() {
    linkedlist *newlst;
    newlst=new linkedlist();
    char *newchars,*pch;

    newchars=strdup((ui.txtTags->text()).toAscii());
    pch = strtok (newchars,",");
    while (pch != NULL) {
	qDebug(pch);
        newlst->add(pch);
        pch = strtok (NULL, ",");
    }
        
    linkedlist *addlst,*removelst;
    linkedlist *tmplst;

    addlst=newlst->minus(tagslst);
    tmplst=newlst->minus(addlst);
    removelst=tagslst->minus(tmplst);
    tmplst->removeAll();
    delete tmplst;

    qDebug("\nAdding tags ...\n");
    tmplst=fileslst->copyList();
    if (!(addlst->isEmpty()))
        while (!(tmplst->isEmpty())) {
            qDebug("%s\t",pch);
            pch=strdup(tmplst->remove());
            clientaddtags(pch,addlst);
            free(pch);
        }

    tmplst->removeAll();
    delete tmplst;

    tmplst=fileslst->copyList();
    
    qDebug("\nRemoving tags ...\n");
    if (!(removelst->isEmpty())) {
        while (!(tmplst->isEmpty())) {
            qDebug("%s\t",pch);
            pch=strdup(tmplst->remove());
            clientremovetags(pch,removelst);
        }
          free(pch);
    }

    removelst->removeAll();
    delete removelst;
    addlst->removeAll();
    delete addlst;
    tmplst->removeAll();
    delete tmplst;
    free(newchars);

}

void TagEditor::setFileName(linkedlist *lst) {
    char *currenttags;
    char *name;
    linkedlist *temp;
    temp = NULL;
    fileslst=lst->copyList();
    name = strdup(lst->remove());
    ui.lblFilenamesTxt->setText(name);
    if (!(lst->isEmpty()))
        ui.lblFilenamesTxt->setText("Multiple Files");
    
    tagslst=clientlisttags(name);
    while ( (!(lst->isEmpty() )) && (!(tagslst->isEmpty()))) {
        name=lst->remove();
        if (temp!=NULL) {
            temp->removeAll();
            delete temp;
            temp=NULL;
        }
        temp=clientlisttags(name);
        if (temp==NULL) {
            tagslst->removeAll();
        } else   
            tagslst->selfintersect(temp);
    }
    if (tagslst->isEmpty()) {
        currenttags=strdup("");
    } else {
        currenttags = tagslst->toCSVString();
    }
    ui.txtTags->setText(currenttags);

    free(currenttags);
    if (temp!=NULL) {
        temp->removeAll();
        delete temp;
        temp=NULL;
    }
    
}
